import 'dart:async';
import 'dart:io' as io;
import 'package:flutter/widgets.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';

/// 自定义蓝牙适配器状态
enum CustomBluetoothAdapterState {
  unknown,
  unavailable,
  unauthorized,
  turningOn,
  on,
  turningOff,
  off
}

// 蓝牙权限管理类
class BluetoothPermissionsManager {
  /// 检查是否已授予所有必要的权限
  static Future<bool> checkAllPermissions() async {
    if (_isAndroid()) {
      // Android 需要检查多个权限
      return await Permission.bluetoothScan.isGranted &&
          await Permission.bluetoothConnect.isGranted &&
          await Permission.locationWhenInUse.isGranted;
    } else if (_isIOS()) {
      // iOS 只需要检查蓝牙权限
      return await _checkIOSPermissions();
    }
    return false;
  }

  /// 检查 iOS 平台的蓝牙权限
  static Future<bool> _checkIOSPermissions() async {
    try {
      // 使用 flutter_blue_plus 提供的权限检查
      final state = await FlutterBluePlus.adapterState.firstWhere(
        (s) => s == BluetoothAdapterState.on,
        orElse: () => BluetoothAdapterState.off,
      );
      if (state == BluetoothAdapterState.on) {
        // 如果蓝牙已开启，通常意味着有权限
        return true;
      } else {
        // 如果蓝牙关闭，回退到 permission_handler 检查
        return await Permission.bluetooth.isGranted;
      }
    } catch (e) {
      debugPrint('Error checking iOS Bluetooth permissions: $e');
      return false;
    }
  }

  /// 监听蓝牙适配器状态变化
  ///
  /// 返回一个 StreamSubscription，用于监听蓝牙适配器状态的变化
  ///
  /// 注意：在 iOS 上，蓝牙适配器状态变化可能不会被触发
  static StreamSubscription<CustomBluetoothAdapterState>
      listenToBluetoothAdapterState(
          void Function(CustomBluetoothAdapterState) onData) {
    return FlutterBluePlus.adapterState.map((state) {
      switch (state) {
        case BluetoothAdapterState.unknown:
          return CustomBluetoothAdapterState.unknown;
        case BluetoothAdapterState.unavailable:
          return CustomBluetoothAdapterState.unavailable;
        case BluetoothAdapterState.unauthorized:
          return CustomBluetoothAdapterState.unauthorized;
        case BluetoothAdapterState.turningOn:
          return CustomBluetoothAdapterState.turningOn;
        case BluetoothAdapterState.on:
          return CustomBluetoothAdapterState.on;
        case BluetoothAdapterState.turningOff:
          return CustomBluetoothAdapterState.turningOff;
        case BluetoothAdapterState.off:
          return CustomBluetoothAdapterState.off;
      }
    }).listen(onData);
  }

  /// 检查蓝牙是否开启
  static Future<bool> get isBluetoothEnabled async {
    return await FlutterBluePlus.isOn;
  }

  /// 请求开启蓝牙 (仅Android)
  static Future<void> requestEnableBluetooth() async {
    if (_isAndroid()) {
      await FlutterBluePlus.turnOn();
    }
  }

  /// 检查是否是Android平台
  static bool _isAndroid() {
    return io.Platform.isAndroid;
  }

  /// 检查是否是iOS平台
  static bool _isIOS() {
    return io.Platform.isIOS;
  }
}
